// 全局变量
let currentPage = 1;
let currentSearch = '';
let currentCategory = '';
let currentSource = '';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    loadTags();
    loadCollections();
    
    // 搜索框事件监听
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchCollections();
        }
    });
});

// 加载分类
async function loadCategories() {
    try {
        const response = await fetch('/api/categories');
        const categories = await response.json();
        
        const categorySelect = document.getElementById('categoryFilter');
        const addCategorySelect = document.getElementById('category');
        const editCategorySelect = document.getElementById('editCategory');
        
        // 清空现有选项
        [categorySelect, addCategorySelect, editCategorySelect].forEach(select => {
            select.innerHTML = '<option value="">选择分类</option>';
        });
        
        // 添加分类选项
        categories.forEach(category => {
            const option = `<option value="${category.id}">${category.name}</option>`;
            [categorySelect, addCategorySelect, editCategorySelect].forEach(select => {
                select.innerHTML += option;
            });
        });
    } catch (error) {
        console.error('加载分类失败:', error);
    }
}

// 加载标签
async function loadTags() {
    try {
        const response = await fetch('/api/tags');
        const tags = await response.json();
        
        const tagCloud = document.getElementById('tagCloud');
        tagCloud.innerHTML = '';
        
        if (tags.length === 0) {
            tagCloud.innerHTML = '<p class="text-muted">暂无标签</p>';
            return;
        }
        
        // 计算标签大小（基于使用频率）
        const tagSizes = calculateTagSizes(tags);
        
        tags.forEach(tag => {
            const size = tagSizes[tag.id] || 1;
            const tagElement = document.createElement('a');
            tagElement.href = '#';
            tagElement.className = `tag tag-size-${size}`;
            tagElement.textContent = tag.name;
            tagElement.onclick = (e) => {
                e.preventDefault();
                filterByTag(tag.name);
            };
            tagCloud.appendChild(tagElement);
        });
    } catch (error) {
        console.error('加载标签失败:', error);
    }
}

// 计算标签大小
function calculateTagSizes(tags) {
    // 这里简化处理，实际应该根据标签使用频率计算
    const sizes = {};
    tags.forEach((tag, index) => {
        sizes[tag.id] = Math.min(5, Math.max(1, Math.floor(Math.random() * 5) + 1));
    });
    return sizes;
}

// 加载收藏列表
async function loadCollections(page = 1) {
    try {
        const params = new URLSearchParams({
            page: page,
            per_page: 10,
            search: currentSearch,
            category_id: currentCategory
        });
        
        const response = await fetch(`/api/collections?${params}`);
        const data = await response.json();
        
        displayCollections(data.collections);
        displayPagination(data);
        currentPage = page;
    } catch (error) {
        console.error('加载收藏失败:', error);
        showError('加载收藏失败，请稍后重试');
    }
}

// 显示收藏列表
function displayCollections(collections) {
    const container = document.getElementById('collectionsList');
    
    if (collections.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-bookmark"></i>
                <h4>暂无收藏</h4>
                <p>点击"添加收藏"开始收集您喜欢的内容</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = collections.map(collection => `
        <div class="card collection-item mb-3">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <h5 class="card-title">
                            <a href="${collection.url || '#'}" class="collection-title" target="_blank">
                                ${highlightSearch(collection.title)}
                            </a>
                        </h5>
                        <div class="collection-meta mb-2">
                            <span class="badge bg-secondary source-badge me-2">${collection.source || '未知'}</span>
                            ${collection.category_name ? `<span class="badge bg-info source-badge me-2">${collection.category_name}</span>` : ''}
                            <small class="text-muted">
                                ${new Date(collection.created_at).toLocaleDateString('zh-CN')}
                            </small>
                        </div>
                        ${collection.content ? `<p class="card-text collection-content">${highlightSearch(collection.content)}</p>` : ''}
                        ${collection.tags && collection.tags.length > 0 ? `
                            <div class="collection-tags">
                                ${collection.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                            </div>
                        ` : ''}
                    </div>
                    <div class="btn-group-vertical btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="editCollection(${collection.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="deleteCollection(${collection.id})" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 高亮搜索关键词
function highlightSearch(text) {
    if (!currentSearch) return text;
    const regex = new RegExp(`(${currentSearch})`, 'gi');
    return text.replace(regex, '<span class="search-highlight">$1</span>');
}

// 显示分页
function displayPagination(data) {
    const container = document.getElementById('pagination');
    
    if (data.pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let html = '';
    
    // 上一页
    if (data.current_page > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadCollections(${data.current_page - 1})">上一页</a></li>`;
    }
    
    // 页码
    const startPage = Math.max(1, data.current_page - 2);
    const endPage = Math.min(data.pages, data.current_page + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        html += `<li class="page-item ${i === data.current_page ? 'active' : ''}">
            <a class="page-link" href="#" onclick="loadCollections(${i})">${i}</a>
        </li>`;
    }
    
    // 下一页
    if (data.current_page < data.pages) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadCollections(${data.current_page + 1})">下一页</a></li>`;
    }
    
    container.innerHTML = html;
}

// 搜索收藏
function searchCollections() {
    currentSearch = document.getElementById('searchInput').value.trim();
    currentPage = 1;
    loadCollections();
}

// 筛选收藏
function filterCollections() {
    currentCategory = document.getElementById('categoryFilter').value;
    currentSource = document.getElementById('sourceFilter').value;
    currentPage = 1;
    loadCollections();
}

// 按标签筛选
function filterByTag(tagName) {
    currentSearch = tagName;
    document.getElementById('searchInput').value = tagName;
    currentPage = 1;
    loadCollections();
}

// 显示添加模态框
function showAddModal() {
    const modal = new bootstrap.Modal(document.getElementById('addCollectionModal'));
    document.getElementById('addCollectionForm').reset();
    modal.show();
}

// 保存收藏
async function saveCollection() {
    const form = document.getElementById('addCollectionForm');
    const formData = new FormData(form);
    
    const data = {
        title: document.getElementById('title').value,
        url: document.getElementById('url').value,
        source: document.getElementById('source').value,
        category_id: document.getElementById('category').value || null,
        tags: document.getElementById('tags').value.split(',').map(tag => tag.trim()).filter(tag => tag),
        content: document.getElementById('content').value
    };
    
    if (!data.title) {
        showError('请输入标题');
        return;
    }
    
    try {
        const response = await fetch('/api/collections', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            bootstrap.Modal.getInstance(document.getElementById('addCollectionModal')).hide();
            showSuccess('收藏添加成功');
            loadCollections();
            loadTags(); // 重新加载标签云
        } else {
            showError('添加收藏失败');
        }
    } catch (error) {
        console.error('保存收藏失败:', error);
        showError('保存收藏失败，请稍后重试');
    }
}

// 编辑收藏
async function editCollection(id) {
    try {
        const response = await fetch(`/api/collections/${id}`);
        const collection = await response.json();
        
        // 填充编辑表单
        document.getElementById('editId').value = collection.id;
        document.getElementById('editTitle').value = collection.title;
        document.getElementById('editUrl').value = collection.url || '';
        document.getElementById('editSource').value = collection.source || '';
        document.getElementById('editCategory').value = collection.category_id || '';
        document.getElementById('editTags').value = collection.tags.join(', ');
        document.getElementById('editContent').value = collection.content || '';
        
        // 显示编辑模态框
        const modal = new bootstrap.Modal(document.getElementById('editCollectionModal'));
        modal.show();
    } catch (error) {
        console.error('加载收藏详情失败:', error);
        showError('加载收藏详情失败');
    }
}

// 更新收藏
async function updateCollection() {
    const id = document.getElementById('editId').value;
    const data = {
        title: document.getElementById('editTitle').value,
        url: document.getElementById('editUrl').value,
        source: document.getElementById('editSource').value,
        category_id: document.getElementById('editCategory').value || null,
        tags: document.getElementById('editTags').value.split(',').map(tag => tag.trim()).filter(tag => tag),
        content: document.getElementById('editContent').value
    };
    
    if (!data.title) {
        showError('请输入标题');
        return;
    }
    
    try {
        const response = await fetch(`/api/collections/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            bootstrap.Modal.getInstance(document.getElementById('editCollectionModal')).hide();
            showSuccess('收藏更新成功');
            loadCollections();
            loadTags(); // 重新加载标签云
        } else {
            showError('更新收藏失败');
        }
    } catch (error) {
        console.error('更新收藏失败:', error);
        showError('更新收藏失败，请稍后重试');
    }
}

// 删除收藏
async function deleteCollection(id) {
    if (!confirm('确定要删除这个收藏吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/collections/${id}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            showSuccess('收藏删除成功');
            loadCollections();
            loadTags(); // 重新加载标签云
        } else {
            showError('删除收藏失败');
        }
    } catch (error) {
        console.error('删除收藏失败:', error);
        showError('删除收藏失败，请稍后重试');
    }
}

// 显示成功消息
function showSuccess(message) {
    // 这里可以使用更优雅的通知组件
    alert(message);
}

// 显示错误消息
function showError(message) {
    // 这里可以使用更优雅的通知组件
    alert('错误: ' + message);
}

